<template>
  <view class="user-register-form p-8 box-border">
    <view
      class="text-[50rpx] font-bold text-black text-center tracking-[50rpx] indent-[50rpx] mb-6"
    >
      <text>用户注册</text>
    </view>
    <view class="form">
      <up-form
        labelPosition="left"
        :model="form"
        :rules="rules"
        ref="uForm"
        labelWidth="85"
        labelAlign="right"
      >
        <up-form-item label="类型：" prop="residenceStatus">
          <up-radio-group v-model="form.residenceStatus" placement="row">
            <up-radio activeColor="#0189FE" :name="0" label="常住"></up-radio>
            <up-radio activeColor="#0189FE" :name="1" label="暂住"></up-radio>
          </up-radio-group>
        </up-form-item>
        <up-form-item label="姓名：" prop="userName">
          <up-input
            v-model="form.userName"
            border="surround"
            color="#000000"
            placeholder="请输入姓名"
            placeholderStyle="{color: '#707070'}"
            clearable
          >
            <template #suffix>
              <view class="flex justify-center">
                <ocr-navigator
                  @onSuccess="idCardOcr"
                  certificateType="idCard"
                  :opposite="false"
                  selectedOptions="['id','name','sex','birthday','homePlace']"
                >
                  <image
                    class="input-suffix-icon"
                    :src="idcardRead"
                    mode="aspectFit"
                  ></image>
                </ocr-navigator>
              </view>
            </template>
          </up-input>
        </up-form-item>
        <up-form-item label="身份证号：" prop="idCard">
          <up-input
            v-model="form.idCard"
            border="surround"
            color="#000000"
            placeholder="请输入身份证号码"
            placeholderStyle="{color: '#707070'}"
            type="idcard"
            clearable
          ></up-input>
        </up-form-item>
        <up-form-item label="手机号：" prop="phonenumber">
          <up-input
            v-model="form.phonenumber"
            border="surround"
            color="#000000"
            placeholder="请输入手机号"
            placeholderStyle="{color: '#707070'}"
            clearable
          ></up-input>
        </up-form-item>
        <up-form-item label="居住地：" prop="communityId">
          <view class="flex flex-wrap justify-between">
            <view class="disable-input" style="width: 26%">
              <up-input
                v-model="form.region"
                border="none"
                color="#707070"
                disabled
              ></up-input>
            </view>
            <view class="disable-input" style="width: 32%">
              <up-input
                v-model="form.street"
                border="none"
                color="#707070"
                disabled
              ></up-input>
            </view>
            <view
              class="select-input-bg-white"
              style="width: 40%"
              @click="showCommunity = true"
            >
              <up-input
                v-model="form.communityName"
                placeholder="社区名称"
                border="none"
                disabled
                disabledColor="#ffffff"
                placeholderStyle="{color: '#707070'}"
                suffixIcon="arrow-down"
                :suffixIconStyle="{ color: '#777777', fontSize: '20rpx' }"
              ></up-input>
            </view>
          </view>
        </up-form-item>
        <up-form-item label="    " prop="buildingId">
          <view class="flex flex-wrap justify-between">
            <view
              class="select-input-bg-white"
              style="width: 38%"
              @click="showStreet = true"
            >
              <up-input
                v-model="form.alleyName"
                placeholder="街路巷"
                border="none"
                disabled
                disabledColor="#ffffff"
                placeholderStyle="{color: '#707070'}"
                suffixIcon="arrow-down"
                :suffixIconStyle="{ color: '#777777', fontSize: '20rpx' }"
              ></up-input>
            </view>
            <!-- <view
              class="select-input-bg-white"
              style="width: 34%"
              @click="showPlot = true"
            >
              <up-input
                v-model="form.subdistrict"
                placeholder="小区名称"
                border="none"
                disabled
                disabledColor="#ffffff"
                placeholderStyle="{color: '#707070'}"
                suffixIcon="arrow-down"
                :suffixIconStyle="{ color: '#777777', fontSize: '20rpx' }"
              ></up-input>
            </view> -->
            <view
              class="select-input-bg-white"
              style="width: 60%"
              @click="showBuild = true"
            >
              <up-input
                v-model="form.building"
                placeholder="门楼牌号"
                border="none"
                disabled
                disabledColor="#ffffff"
                placeholderStyle="{color: '#707070'}"
                suffixIcon="arrow-down"
                :suffixIconStyle="{ color: '#777777', fontSize: '20rpx' }"
              ></up-input>
            </view>
          </view>
        </up-form-item>
        <up-form-item label="    ">
          <view class="flex flex-wrap justify-between">
            <view class="input-bg-white" style="width: 100%">
              <up-input
                v-model="form.house"
                border="none"
                color="#000000"
                placeholder="输入户号 例如:1-1"
                placeholderStyle="{color: '#707070'}"
                clearable
              ></up-input>
            </view>
          </view>
        </up-form-item>
      </up-form>
    </view>
    <view class="w-[100%] mt-7">
      <up-checkbox
        label="我已认真阅读并同意《用户服务协议》及《隐私协议》"
        name="agree"
        usedAlone
        v-model:checked="isAgree"
      >
      </up-checkbox>
    </view>
    <button
      class="btn-0189FE h-[83rpx] leading-[83rpx] text-[33rpx] mt-4"
      @click="onsubmit"
    >
      确 认
    </button>
    <up-popup :show="showTip" :round="8" mode="center">
      <view
        class="px-6 py-5 box-border flex flex-col justify-center items-center w-[75vw]"
      >
        <up-icon
          name="checkmark-circle-fill"
          color="#33A954"
          size="70"
        ></up-icon>
        <text
          class="text-black text-[33rpx] text-center mt-4 w-[70%] leading-[48rpx]"
          >注册成功，3s后自动登录跳转到首页</text
        >
      </view>
    </up-popup>
    <!-- 社区 -->
    <up-action-sheet
      :show="showCommunity"
      :actions="communitys"
      title="请选择社区"
      @close="showCommunity = false"
      @select="communitySelect"
    >
    </up-action-sheet>
    <!-- 街路巷 -->
    <up-action-sheet
      :show="showStreet"
      :actions="streets"
      title="请选择街路巷"
      @close="showStreet = false"
      @select="streetSelect"
    >
    </up-action-sheet>
    <!-- 小区 -->
    <up-action-sheet
      :show="showPlot"
      :actions="plots"
      title="请选择小区"
      @close="showPlot = false"
      @select="plotSelect"
    >
    </up-action-sheet>
    <!-- 门楼牌号 -->
    <up-action-sheet
      :show="showBuild"
      :actions="buildings"
      title="请选择门楼牌号"
      @close="showBuild = false"
      @select="buildSelect"
    >
    </up-action-sheet>
    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>

<script setup lang="ts">
import { OCRRecognize, crowdRegister } from "@/api/index";
import {
  communityGroup,
  selectAlleyList,
  selectSubdistrictList,
  selectBuildingList,
} from "@/api/community/index";
import { crowdUserInfo } from "@/api/user";
import { qqmapKey } from "@/config/app";
import { getCommunityByPoint } from "@/api/user";
import { useUserInfoStore } from "@/stores/userInfo";
const userInfoStore = useUserInfoStore();
import idcardRead from "@/static/icon/idcardRead.png";

const uToastRef = <any>ref(null);
const uForm = <any>ref(null);
const data = reactive({
  showCommunity: false,
  communitys: <any>[],
  showStreet: false,
  streets: <any>[],
  showPlot: false,
  plots: <any>[],
  showBuild: false,
  buildings: <any>[],
  form: {
    userName: undefined,
    idCard: undefined,
    phonenumber: userInfoStore.userInfo.wxPhone,
    region: "北碚区",
    street: "朝阳街道",
    communityId: undefined,
    communityName: undefined,
    subdistrict: "", //所属小区
    subdistrictId: "",
    building: undefined,
    buildingId: undefined,
    openId: userInfoStore.userInfo.wxOpenId,
    vxPhone: userInfoStore.userInfo.wxPhone,
    residenceStatus: 0,
    alleyName: undefined,
    alleyId: undefined,
    house: "",
  },
  rules: {
    residenceStatus: {
      type: "number",
      required: true,
      message: "请选择类型",
      trigger: ["blur", "change"],
    },
    userName: {
      type: "string",
      required: true,
      message: "请填写姓名",
      trigger: ["blur", "change"],
    },
    idCard: [
      {
        type: "string",
        required: true,
        message: "请填写身份证号",
        trigger: ["blur", "change"],
      },
      {
        validator: (rule: any, value: any, callback: any) => {
          return uni.$u.test.idCard(value);
        },
        message: "身份证号不正确",
        trigger: ["change", "blur"],
      },
    ],
    phonenumber: [
      {
        type: "string",
        required: true,
        message: "请填写手机号码",
        trigger: ["blur", "change"],
      },
      {
        validator: (rule: any, value: any, callback: any) => {
          return uni.$u.test.mobile(value);
        },
        message: "手机号码不正确",
        trigger: ["change", "blur"],
      },
    ],
    communityId: {
      type: "number",
      required: true,
      message: "居住地请选择所属社区",
      trigger: ["blur", "change"],
    },
    buildingId: {
      type: "number",
      required: true,
      message: "居住地请选择门楼牌号",
      trigger: ["blur", "change"],
    },
  },
  isAgree: false,
});
const {
  showCommunity,
  communitys,
  showStreet,
  streets,
  showPlot,
  plots,
  showBuild,
  buildings,
  form,
  rules,
  isAgree,
} = toRefs(data);

const showTip = ref(false);
const timer = <any>ref(null);

// 社区选择
const communitySelect = (e: any) => {
  form.value.communityName = e.name;
  form.value.communityId = e.id;
  resetData(1);
  getAlleyList();
};
// 街路巷选择
const streetSelect = (e: any) => {
  form.value.alleyName = e.name;
  form.value.alleyId = e.id;
  resetData(2);
  getPlotList();
  getBuildingList();
};
// 小区选择
const plotSelect = (e: any) => {
  form.value.subdistrict = e.name;
  form.value.subdistrictId = e.id;
  resetData(3);
  getBuildingList();
};
// 门楼牌号选择
const buildSelect = (e: any) => {
  form.value.building = e.name;
  form.value.buildingId = e.id;
};
// 获取社区下拉数据
const getCommunityList = () => {
  communityGroup()
    .then((res: any) => {
      const { data } = res;
      communitys.value = data ?? [];
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 获取街路巷数据
const getAlleyList = () => {
  selectAlleyList({ communityId: form.value.communityId })
    .then((res: any) => {
      const { data } = res;
      streets.value = data ?? [];
      if (streets.value.length) {
        streets.value = streets.value.map((item: any) => {
          item.name = item.alleyName;
          return item;
        });
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 获取小区数据
const getPlotList = () => {
  selectSubdistrictList({ alleyId: form.value.alleyId })
    .then((res: any) => {
      const { data } = res;
      plots.value = data ?? [];
      if (plots.value.length) {
        plots.value = plots.value.map((item: any) => {
          item.name = item.subdistrictName;
          return item;
        });
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 获取门楼牌号数据
const getBuildingList = () => {
  selectBuildingList({
    alleyId: form.value.alleyId,
    subId: form.value.subdistrictId,
  })
    .then((res: any) => {
      const { data } = res;
      buildings.value = data ?? [];
      if (buildings.value.length) {
        buildings.value = buildings.value.map((item: any) => {
          item.name = item.buildingName;
          return item;
        });
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
const resetData = (type: number) => {
  if (type <= 1) {
    form.value.alleyName = "";
    form.value.alleyId = "";
  }
  if (type <= 2) {
    form.value.subdistrict = "";
    form.value.subdistrictId = "";
  }
  if (type <= 3) {
    form.value.building = "";
    form.value.buildingId = "";
  }
};
// 身份证识别
const idCardOcr = (e: any) => {
  console.log(e);
  if (e.detail) {
    form.value.idCard = e.detail.id.text;
    form.value.userName = e.detail.name.text;
  }
};
// 提交表单
const onsubmit = () => {
  uForm.value
    .validate()
    .then((res: any) => {
      if (isAgree.value) {
        uni.showLoading({
          title: "提交中",
          mask: true,
        });
        crowdRegister(form.value)
          .then(async (res1: any) => {
            uni.hideLoading();
            const { data } = res1;
            await userInfoStore.setToken(data.token);
            await userInfoStore.setUserInfo(data);
            await getCrowdUserInfo();
            showTip.value = true;
            if (timer) clearTimeout(timer);
            timer.value = setTimeout(() => {
              close();
              clearTimeout(timer);
            }, 3000);
          })
          .catch((err: any) => {
            uni.hideLoading();
            uToastRef.value.show({
              type: "error",
              message: err,
            });
          });
      } else {
        uni.$u.toast("请先同意服务协议及隐私协议");
      }
    })
    .catch(() => {});
};
// 获取群众个人信息
const getCrowdUserInfo = () => {
  crowdUserInfo({ crowdUserId: userInfoStore.userInfo.userId })
    .then((res: any) => {
      const { data } = res;
      userInfoStore.setCrowdInfo(data);
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 关闭提示弹框
const close = () => {
  showTip.value = false;
  uni.redirectTo({
    url: "/pages/crowd/home/index",
  });
};
// 获取用户所在位置
const getLocation = () => {
  // 实例化腾讯API核心类
  // let qqmapsdk = new QQMapWX({ key: qqmapKey });
  uni.getLocation({
    type: "gcj02",
    success: function (res) {
      getCommunityByPoint({ lat: res.latitude, lnt: res.longitude })
        .then((res1: any) => {
          const { data } = res1;
          if (data.withinFenceStatus) {
            form.value.communityName = data.communityName;
            form.value.communityId = data.communityId;
          }
        })
        .catch((err: any) => {
          uToastRef.value.show({
            type: "error",
            message: err,
          });
        });
    },
    fail: function (err) {
      uToastRef.value.show({
        type: "error",
        message: "当前位置信息获取失败",
      });
    },
  });
};

onLoad(() => {
  getCommunityList();
  getLocation();
});

onReady(() => {
  uForm.value.setRules(rules.value);
});
</script>

<style lang="scss" scoped>
.user-register-form {
  ::v-deep {
    .u-radio-group {
      justify-content: flex-start;
      .u-radio:last-child {
        margin-left: 30rpx;
      }
    }
  }
  .input-suffix-icon {
    width: 50rpx;
    height: 40rpx;
  }
  ::v-deep .u-form-item:last-child .u-form-item__body__left {
    align-items: baseline;
  }
  ::v-deep .u-form-item:nth-last-child(2) .u-form-item__body {
    padding: 0;
  }
  .disable-input {
    ::v-deep input {
      background: #e6e6e6;
      border: 1rpx solid #707070;
      border-radius: 8rpx;
      padding: 6rpx 10rpx;
    }
  }
  .select-input-bg-white {
    ::v-deep .u-input__content {
      background-color: #fff;
      border: 1rpx solid #707070;
      border-radius: 8rpx;
      padding: 6rpx 10rpx;
    }
  }
  .input-bg-white {
    ::v-deep input {
      background-color: #fff;
      border: 1rpx solid #707070;
      border-radius: 8rpx;
      padding: 6rpx 10rpx;
    }
  }
  ::v-deep .u-border {
    border: 1rpx solid #707070;
    background-color: #fff;
  }
  ::v-deep .u-checkbox {
    align-items: baseline;
  }
  ::v-deep .u-action-sheet__item-wrap {
    max-height: 45vh !important;
  }
}
::v-deep .u-action-sheet__item-wrap {
  max-height: 50vh !important;
}
</style>
